package com.taoyibao.hongcanting.ui;

import android.Manifest;
import android.animation.Animator;
import android.animation.AnimatorInflater;
import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.support.annotation.RequiresApi;
import android.support.v4.app.Fragment;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.RelativeLayout;

import com.taoyibao.hongcanting.R;
import com.taoyibao.hongcanting.base.activity.BaseActivityNoSlidePresenter;
import com.taoyibao.hongcanting.cache.SpUtils;
import com.taoyibao.hongcanting.constant.CodeConstant;
import com.taoyibao.hongcanting.constant.NetCode;
import com.taoyibao.hongcanting.dialog.DialogUpdataVersion;
import com.taoyibao.hongcanting.dialog.LoadingDialog;
import com.taoyibao.hongcanting.event.EventCurrentPage;
import com.taoyibao.hongcanting.event.EventFinishActivity;
import com.taoyibao.hongcanting.event.EventHomeRefresh;
import com.taoyibao.hongcanting.event.EventInstallApk;
import com.taoyibao.hongcanting.event.EventMenu;
import com.taoyibao.hongcanting.event.EventMusic;
import com.taoyibao.hongcanting.event.EventMusicAnimator;
import com.taoyibao.hongcanting.http.DefaultTransformer;
import com.taoyibao.hongcanting.http.JsonApiWrapper;
import com.taoyibao.hongcanting.http.ProgressSubscriber;
import com.taoyibao.hongcanting.model.AppVersionModel;
import com.taoyibao.hongcanting.model.CompanyBaseModel;
import com.taoyibao.hongcanting.model.OrderPageModel;
import com.taoyibao.hongcanting.model.UserTableModel;
import com.taoyibao.hongcanting.service.DownApkServer;
import com.taoyibao.hongcanting.service.MusicService;
import com.taoyibao.hongcanting.ui.entertainment.fragment.EntertainmentFragment;
import com.taoyibao.hongcanting.ui.home.activity.MenuActivity;
import com.taoyibao.hongcanting.ui.home.delegate.MainDeleget;
import com.taoyibao.hongcanting.ui.home.fragment.HomeFragment;
import com.taoyibao.hongcanting.ui.login.activity.LoginActivity;
import com.taoyibao.hongcanting.ui.mine.activity.WaitPayActivity;
import com.taoyibao.hongcanting.ui.mine.fragment.MineFragment;
import com.taoyibao.hongcanting.ui.restaurant.fragment.RestaurantFragment;
import com.taoyibao.hongcanting.utils.AppUtils;
import com.taoyibao.hongcanting.utils.CodeUtils;
import com.taoyibao.hongcanting.utils.LogUtils;
import com.taoyibao.hongcanting.utils.ToastUtils;
import com.taoyibao.hongcanting.utils.permission.MPermission;
import com.taoyibao.hongcanting.utils.permission.OnMPermissionDenied;
import com.taoyibao.hongcanting.utils.permission.OnMPermissionGranted;
import com.taoyibao.hongcanting.utils.permission.OnMPermissionNeverAskAgain;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 首页
 */
public class MainActivity extends BaseActivityNoSlidePresenter<MainDeleget> implements DialogUpdataVersion.DialogDownloadInter, View.OnClickListener {

    private static final String TAG = "MainActivity";
    private DialogUpdataVersion mDialogUpdataVersion;
    /**
     * 权限请求码
     */
    private static final int REQUEST_CODE_PERMISSION = 1000;
    //需要申请的权限的数组
    private String[] mPermissions = {Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE/*,
            Manifest.permission.REQUEST_INSTALL_PACKAGES*/};
    /**
     * 版本更新的下载地址
     */
    private String mUpDataUrl;
    private LoadingDialog mLoadingDialog;
    private String mVersionName;//App的版本名称用于下载命名使用
    private RelativeLayout mLayoutMenu;
    private Animator mAnimator;//点餐按钮的动画
    private String mOrderId;
    private MusicService mMusicService;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        viewDelegate.setFragmentManager(getSupportFragmentManager());
        super.onCreate(savedInstanceState);
    }

    @Override
    protected Class<MainDeleget> getDelegateClass() {
        return MainDeleget.class;
    }

    @Override
    protected void bindEvenListener() {
        super.bindEvenListener();
        EventBus.getDefault().register(this);
        bindToService();
        mLayoutMenu = viewDelegate.get(R.id.layout_main_menu);
        mLayoutMenu.setOnClickListener(this);
        SpUtils.putOtherSeatName("");
        SpUtils.putOtherSeatId("");
        initFragment();
        mDialogUpdataVersion = new DialogUpdataVersion();
        mDialogUpdataVersion.setDownloadInter(this);
        getServiceVersionInfo();
        setAnimation();

    }


    /**
     * 初始化数据
     */
    private void initFragment() {
        List<Fragment> fragmentList = new ArrayList<>();
        fragmentList.add(new HomeFragment());
        fragmentList.add(new RestaurantFragment());
        fragmentList.add(new EntertainmentFragment());
        fragmentList.add(new MineFragment());
        viewDelegate.addFragment(fragmentList);
    }


    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    protected void onResume() {
        super.onResume();
        if (SpUtils.getLoginStatus()) {//登录状态 查看用户用餐状态
            getTableStatus();
            getWaitPayOrder();

        }
        mAnimator.resume();
    }

    /**
     * 获取当前用户的就餐状态
     */
    public void getTableStatus() {
        JsonApiWrapper.getApiService().tableStatus(SpUtils.getToken())
                .compose(new DefaultTransformer<CompanyBaseModel<List<UserTableModel>>>())
                .subscribe(new ProgressSubscriber<CompanyBaseModel<List<UserTableModel>>>(this, false) {
                    @Override
                    public void onNext(CompanyBaseModel<List<UserTableModel>> result) {
                        if (result.code == NetCode.HTTP_200 && result.data != null && result.data.size() > 0) {
                            UserTableModel userTableModel = result.data.get(0);
                            if (userTableModel != null && !TextUtils.isEmpty(userTableModel.desk_code)) {
                                viewDelegate.setTable(userTableModel.desk_code);
                            } else {
                                viewDelegate.setTable("");
                            }
                        } else {
                            viewDelegate.setTable("");
                        }
                    }
                });
    }

    /**
     * 判断是否有未支付订单
     */
    public void getWaitPayOrder() {
        JsonApiWrapper.getApiService().userOrders(SpUtils.getToken(), SpUtils.getMemberId(), CodeConstant.ORDER_STATUS_NOPAY, 1, 1000)
                .compose(new DefaultTransformer<CompanyBaseModel<OrderPageModel>>())
                .subscribe(new ProgressSubscriber<CompanyBaseModel<OrderPageModel>>(this, false) {
                    @Override
                    public void onNext(CompanyBaseModel<OrderPageModel> orderPageModel) {
                        if (orderPageModel.code == NetCode.HTTP_200) {
                            if (orderPageModel.data != null && orderPageModel.data != null &&
                                    orderPageModel.data.orders_info != null && orderPageModel.data.orders_info.size() > 0) {//有未支付订单
                                mOrderId = orderPageModel.data.orders_info.get(0).order_id;
                            } else {//没有未支付订单
                                mOrderId = "";
                            }
                        } else {
                            mOrderId = "";
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        mOrderId = "";
                    }
                });
    }


    /**
     * 收到切换页面的消息
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void setCurrentPage(EventCurrentPage event) {
        if (TextUtils.equals(event.target, "MainActivity")) {
            viewDelegate.setCurrentPage(event.mCurrentPage);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
            mLoadingDialog = null;
        }
        //结束动画
        if (mAnimator != null && mAnimator.isStarted()) {
            mAnimator.end();
        }
        unbindService(conn);
    }

    /**
     * 关闭首页
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void eventFinish(EventFinishActivity event) {
        if (event.mainAvtivity) {
            finish();
        }
    }


    //声明一个long类型变量：用于存放上一点击“返回键”的时刻
    private long mExitTime;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //判断用户是否点击了“返回键”
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            //与上次点击返回键时刻作差
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                //大于2000ms则认为是误操作，使用Toast进行提示
                ToastUtils.showToast(CodeUtils.getIdString(R.string.dialog_isQuit));
                //并记录下本次点击“返回键”的时刻，以便下次进行判断
                mExitTime = System.currentTimeMillis();
            } else {
                //小于2000ms则认为是用户确实希望退出程序-调用System.exit()方法进行退出
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 获取服务器上的版本信息
     */
    public void getServiceVersionInfo() {
        JsonApiWrapper.getApiService().appLevel(0)
                .compose(new DefaultTransformer<CompanyBaseModel<List<AppVersionModel>>>())
                .subscribe(new ProgressSubscriber<CompanyBaseModel<List<AppVersionModel>>>(this, false) {
                    @Override
                    public void onNext(CompanyBaseModel<List<AppVersionModel>> result) {
                        if (result.code == NetCode.HTTP_200 && result.data != null && result.data.size() > 0) {//有版本信息
                            AppVersionModel appVersionModel = result.data.get(0);
                            if (appVersionModel.versionCode > AppUtils.getVersonCode()) {//对比版本号 需要更新
                                mUpDataUrl = appVersionModel.downloadUrl;
                                mDialogUpdataVersion.setUIData(appVersionModel.isForce, appVersionModel.versionName, appVersionModel.updateContent);
                                mDialogUpdataVersion.showDilaog(getSupportFragmentManager(), "ATG");
                                mVersionName = appVersionModel.versionName;
                            }
                        }
                    }
                });
    }

    /**
     * 立即更新
     *
     * @param isForce
     */
    @Override
    public void onDownload(int isForce) {
        //先判断本地是否已经下载
        String apkName = SpUtils.getApkName();
        File file = null;
        if (!TextUtils.isEmpty(apkName)) {
            file = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS + "/" + apkName);
        }

        if (file != null && file.exists() && file.isFile()) {//已经下载过了
            installApk();
        } else {//没有下载过的，重新下载
            requestBasicPermission(mPermissions, REQUEST_CODE_PERMISSION);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                           int[] grantResults) {
        MPermission.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    //同意
    @RequiresApi(api = Build.VERSION_CODES.M)
    @OnMPermissionGranted(REQUEST_CODE_PERMISSION)
    public void onBasicPermissionSuccess() {
        startDownload();
    }

    //拒绝
    @OnMPermissionDenied(REQUEST_CODE_PERMISSION)
    public void onBasicPermissionFailed() {
        ToastUtils.showToast(CodeUtils.getIdString(R.string.string_hintPermission));
    }

    //不再提醒
    @OnMPermissionNeverAskAgain(REQUEST_CODE_PERMISSION)
    public void onBasicPermissionNeverAskAgain() {
        ToastUtils.showToast(CodeUtils.getIdString(R.string.string_hintPermission));
    }

    /**
     * 基本权限管理
     */
    private void requestBasicPermission(String[] permission, int requestCode) {
        MPermission.with(this)
                .addRequestCode(requestCode)
                .permissions(
                        permission
                ).request();
    }

    /**
     * 开始下载
     */
    public void startDownload() {
        mLoadingDialog = new LoadingDialog(this);
        mLoadingDialog.setText("正在下载中...");
        mLoadingDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    return true;
                }
                return false;
            }
        });
        mLoadingDialog.show();

        //先判断当前手机是否可以使用DownloadManager
        if (AppUtils.canDownloadState()) {
            LogUtils.dNormal("UpdateVersion", "DownloadManager 可用");
            Intent downloadApkIntent = new Intent(this, DownApkServer.class);
            Bundle bundle = new Bundle();
            bundle.putString("downloadUrl", mUpDataUrl);
            bundle.putString("title", AppUtils.getAppName());
            bundle.putString("versionName", mVersionName);
            downloadApkIntent.putExtra("download", bundle);
            startService(downloadApkIntent);
        } else {
            LogUtils.dNormal("UpdateVersion", "DownloadManager 不可用");
            Intent intent = new Intent();
            intent.setAction("android.intent.action.VIEW");
            Uri content_url = Uri.parse(mUpDataUrl);
            intent.setData(content_url);
            startActivity(intent);
        }
    }

    /**
     * 安装Apk
     */
    public void installApk() {
        String apkName = SpUtils.getApkName();
        if (!TextUtils.isEmpty(apkName)) {
            LogUtils.dNormal(TAG, "apkName 为" + apkName);
            File file = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS + "/" + apkName);
            if (file != null) {
                Uri uri;
                Intent install = new Intent("android.intent.action.VIEW");
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { //如果是7.0以上的系统，要使用FileProvider的方式构建
                    uri = FileProvider.getUriForFile(this, CodeConstant.PROVIDER_STR, file);
                } else {
                    uri = Uri.fromFile(file);
                }
                install.setDataAndType(uri, "application/vnd.android.package-archive");
                install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                startActivity(install);
            } else {
                LogUtils.dNormal(TAG, "下载失败");
            }
        } else {
            LogUtils.dNormal(TAG, "apkName 为 null");
        }
    }

    /**
     * 下载成功收到消息
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventInstallApk(EventInstallApk result) {
        if (result.isSucess) {
            dismissLoad();
            installApk();
        }
    }

    /**
     * 关闭正在下载的弹窗
     */
    public void dismissLoad() {
        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.layout_main_menu://点餐
                onClickMenu();
                break;
        }
    }


    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    protected void onPause() {
        super.onPause();
        mAnimator.pause();
    }

    /**
     * 设置点餐按钮的动画
     */
    @SuppressLint("ResourceType")
    public void setAnimation() {
        mAnimator = AnimatorInflater.loadAnimator(this, R.anim.anim_diancan);
        mAnimator.setTarget(mLayoutMenu);
        mAnimator.start();
    }

    /**
     * 点餐按钮的事件
     */
    public void onClickMenu() {
        if (SpUtils.getLoginStatus()) {
            if (!TextUtils.isEmpty(mOrderId)) {
                //就餐中 跳转到待支付订单页面
                WaitPayActivity.open(this, mOrderId);
            } else {
                MenuActivity.open(this);
            }
        } else {
            LoginActivity.open(this, "");
        }
    }

    /**
     * 点餐按钮的事件
     * 餐厅地图中点餐按钮传递事件
     *
     * @param eventMenu
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMenuMessage(EventMenu eventMenu) {
        onClickMenu();
    }

    //绑定服务MusicService
    private void bindToService() {
        Intent intent = new Intent(this, MusicService.class);
        bindService(intent, conn, Context.BIND_AUTO_CREATE);
    }

    //绑定服务时的ServiceConnection参数
    private ServiceConnection conn = new ServiceConnection() {
        //绑定成功后该方法回调，并获得服务端IBinder的引用
        public void onServiceConnected(ComponentName name, IBinder service) {
            //通过获得的IBinder获取PlayMusicService的引用
            mMusicService = ((MusicService.MusicBinder) service).getService();
            playMusic();
            isMusicController = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    //播放音乐
    @SuppressLint("ResourceType")
    protected void playMusic() {
        if (mMusicService != null) {
            mMusicService.play();
            //发送消息开始动画
            EventBus.getDefault().post(new EventMusicAnimator(true));
        }
    }

    /**
     * 暂停播放
     */
    public void stopMusic() {
        if (mMusicService != null) {
            mMusicService.stopMusic();
            //发送消息停止播放动画
            EventBus.getDefault().post(new EventMusicAnimator(false));
        }
    }

    /**
     * 手动控制的音乐是否播放
     */
    private boolean isMusicController;

    /**
     * 音乐播放器的控制
     *
     * @param eventMusic
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMusicMessage(EventMusic eventMusic) {
        if (eventMusic.isAppFrontBackHelper) {//前后台切换
            if (eventMusic.isBack) {//进入后台
                stopMusic();
            } else if (isMusicController) {
                playMusic();
            }
        } else {//手动切换
            if (isMusicController) {
                stopMusic();
                isMusicController = false;
            } else {
                playMusic();
                isMusicController = true;
            }
        }
    }

    /**
     * 首页刷新时收到消息
     *
     * @param eventHomeRefresh
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onHomeRefresh(EventHomeRefresh eventHomeRefresh) {
        if (eventHomeRefresh.isRefresh) {
            if (SpUtils.getLoginStatus()) {//登录状态 查看用户用餐状态
                getTableStatus();
                getWaitPayOrder();
            }
        }
    }


}
